﻿using JuCheap.Store.DataService;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace JuCheap.Core.Service
{
    /// <summary>
    /// 依赖注入模块初始化
    /// </summary>
    public static class JuCheapServiceModuleInitialize
    {
        /// <summary>
        /// 添加需要依赖注入的服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddJuCheapService(this IServiceCollection services)
        {

            services.AddScoped(typeof(IBaseDataService<>), typeof(BaseDataService<>));

            //通过反射，批量取出需要注入的服务接口和服务实现类
            var serviceRegistrations =
                from type in typeof(JuCheapServiceModuleInitialize).Assembly.GetTypes()
                where type.Namespace != null && type.Namespace.Contains("JuCheap.Store.Service") &&
                                               type.GetInterfaces().Any(x => x.Name.EndsWith("Service")) &&
                                               type.GetInterfaces().Any()
                select new { Service = type.GetInterfaces().First(), Implementation = type };

            foreach (var t in serviceRegistrations)
            {
                services.AddScoped(t.Service, t.Implementation);
            }
        }
    }
}
